<template>
  <view class="w-full flex image-upload flex-wrap">
    <view
      class="w-[25%] mt-[20rpx]"
      v-for="(i, index) in props.imgs"
      :key="i"
      :style="{ marginLeft: index % 3 == 0 ? 0 : '3%' }"
    >
      <view class="w-full pt-[100%] relative">
        <view
          class="absolute top-0 left-0 w-full h-full flex items-center justify-center border-1 border-[#bfbfbf] border-solid box-border rounded-3 overflow-hidden upload-box"
        >
          <image
            v-if="i.extname !== 'mp4'"
            :src="i.url"
            mode="aspectFill"
            @click.stop="() => previewImg(i.url)"
          />
          <video v-if="i.extname === 'mp4'" :src="i.url"></video>
          <uni-icons
            @click.stop="() => del(index)"
            class="absolute top-0 right-0"
            color="rgba(0,0,0,0.5)"
            type="clear"
            size="30"
          ></uni-icons>
        </view>
      </view>
    </view>

    <view
      class="w-[25%] mt-[20rpx]"
      :style="{ marginLeft: props.imgs.length % 3 ? '3%' : 0 }"
      v-if="props.imgs.length < 1"
    >
      <view class="w-full relative" @click="chooseMedia">
        <div
          class="border-1 border-[#bfbfbf] flex border-solid box-border rounded-3 desc-box"
        >
          <uni-icons
            class="icon-add"
            type="plusempty"
            color="#bfbfbf"
            size="30"
          ></uni-icons>
          <view class="upload-desc">{{ props.text }}</view>
        </div>
      </view>
    </view>
  </view>
</template>
<script lang="ts" setup>
const emits = defineEmits(["select-handle", "delete-images-fun"]);
const selectHandle = (e: string) => emits("select-handle", e);
const deleteImagesFun = (e: string) => emits("delete-images-fun", e);
const count = ref(1);
const props = defineProps<{
  imgs: any[];
}>();

const del = (index) => {
  deleteImagesFun(index);
};

const previewImg = (current) => {
  uni.previewImage({
    current,
    urls: props.imgs.map((item: any) => {
      return item.url;
    }),
  });
};
const chooseMedia = () => {
  uni.chooseMedia({
    count: count.value - props.imgs.length,
    mediaType: props.mediaType,
    sourceType: ["album", "camera"],
    maxDuration: props.max ?? 20,
    camera: "back",
    success(res: any) {
      console.log(res);
      if (res.tempFiles.length > 0) {
        res.tempFiles.forEach((item: any) => {
          console.log(item);
          item.size > 20 * 1024 * 1024
            ? uni.showToast({
                title: "文件大小不能超过20M",
                icon: "none",
              })
            : selectHandle(res);
        });
      }
    },
  });
};
</script>
<style lang="scss" scoped>
.upload-desc {
  width: 100%;
  font-size: 12px;
  text-align: center;
  color: #bfbfbf;
}
.desc-box {
  height: 176rpx;
  justify-content: center;
  flex-direction: column;
}
.icon-add {
  text-align: center;
}
</style>
